# coding:utf-8
from odoo import models, fields, api, _
from odoo.exceptions import Warning
from odoo.tools.float_utils import float_compare


class OLPurchaseOrderExtend(models.Model):
    _inherit = ["purchase.order", "stock.view.quant.mixin"]
    _name = "purchase.order"
    _order = "sequence, date_order desc, id desc"

    user_id = fields.Many2one("res.users", string="Purchase User")
    sequence = fields.Integer(string="Sequence", default=100)
    emergent = fields.Boolean(string="Emergent", default=False)
    not_emergent = fields.Boolean(string='Not Emergent', default=True)
    pr_id = fields.Many2one('purchase.request.order', string='Purchase Request Order')
    attachment_ids = fields.Many2many('ir.attachment', string='附件')
    department_id = fields.Many2one('hr.department', string=u'采购部门', compute='_compute_department', store=True)

    @api.multi
    def _compute_department(self):
        for order in self:
            order.department_id = order.user_id.employee_ids and order.user_id.employee_ids[0].department_id and order.user_id.employee_ids[0].department_id.id or False

    @api.depends('state', 'order_line.qty_invoiced', 'order_line.qty_received', 'order_line.product_qty', 'partner_ref')
    def _get_invoiced(self):
        precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')
        for order in self:
            if order.state not in ('purchase', 'done'):
                order.invoice_status = 'no'
                continue

            if any(float_compare(-1 if line.product_id.purchase_method == 'receive' and round(line.qty_received, 0) == 0 else line.qty_invoiced, line.product_qty if line.product_id.purchase_method == 'purchase' else line.qty_received, precision_digits=precision) == -1 for line in order.order_line):
                order.invoice_status = 'to invoice'
            elif all(float_compare(line.qty_invoiced, line.product_qty if line.product_id.purchase_method == 'purchase' else line.qty_received, precision_digits=precision) >= 0 for line in order.order_line):
                order.invoice_status = 'invoiced'
            else:
                order.invoice_status = 'no'

    @api.multi
    def toggle_emergent(self):
        for record in self:
            record.emergent = not record.emergent
            record.not_emergent = not record.emergent
            if record.emergent:
                record.sequence = 1
            else:
                record.sequence = 100

    @api.multi
    def action_view_quants(self):
        self.ensure_one()
        products = self.order_line.mapped("product_id")
        return self.action_view_quant_by_product_ids(products.ids)

    @api.onchange('requisition_id')
    def _onchange_requisition_id(self):
        if not self.requisition_id:
            return

        requisition = self.requisition_id
        if self.partner_id:
            partner = self.partner_id
        else:
            partner = requisition.vendor_id
        payment_term = partner.property_supplier_payment_term_id
        currency = partner.property_purchase_currency_id or requisition.company_id.currency_id

        # FiscalPosition = self.env['account.fiscal.position']
        # fpos = FiscalPosition.get_fiscal_position(partner.id)
        # fpos = FiscalPosition.browse(fpos)

        self.partner_id = partner.id
        # self.fiscal_position_id = fpos.id
        self.payment_term_id = payment_term.id,
        self.company_id = requisition.company_id.id
        self.currency_id = currency.id
        self.partner_ref = requisition.name # to control vendor bill based on agreement reference
        self.notes = requisition.description
        self.date_order = requisition.date_end or fields.Datetime.now()
        self.picking_type_id = requisition.picking_type_id.id

    def button_confirm(self):
        for order in self:
            if any(line.product_purchase_limit_control and line.product_qty > line.product_purchase_limit
                   for line in order.order_line):
                raise Warning(_("Product quantity must less then product purchase limit."))
            # for line in order.order_line:
            #     line.product_id.last_purchase_price = line.product_id.current_purchase_price
            #     line.product_id.current_purchase_price = line.price_unit
        return super(OLPurchaseOrderExtend, self).button_confirm()
